package com.archstoday.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.archstoday.R;
import com.archstoday.adapter.ChoiceAddressAdapter;
import com.archstoday.common.AsRes;
import com.archstoday.common.SpfUtils;
import com.archstoday.entity.BaseEntity;
import com.archstoday.entity.ChoiceAddressEntity;
import com.archstoday.entity.UserInfoEntity;
import com.archstoday.utils.OAuthUtils;
import com.archstoday.utils.ToolUtils;
import com.base.http.common.BaseHttpClient;
import com.base.utils.MySharedPreferencesMgr;
import com.gifdialog.DialogUtil;
import com.gifdialog.GifDialog;

import java.util.List;

/**
 * 选择所在地
 */
public class ChoiceAddressActivity extends AsBaseActivity {

    private final int CHOICE_ADDRESS = 0x000101;

    private TextView mTitleTv;
    private ListView mList;

    private ChoiceAddressAdapter mAdapter;

    private GifDialog loadingDialog;

    private int mType;
    String province = "";
    String city = "";
    String district = "";

    String iProvince = "";
    String iCity = "";
    String iDistrict = "";
    String key = "";

    @Override
    protected void initView(Bundle bundle) {
        setContentView(R.layout.activity_choice_address);
        mTitleTv = (TextView) findViewById(R.id.title_tv);
        mList = (ListView) findViewById(R.id.choice_list);
    }

    @Override
    protected void initData(Bundle bundle) {
        mType = getIntent().getIntExtra("type", 1);
        switch (mType) {
            case 1:
                mTitleTv.setText("省份");
                iProvince = getIntent().getStringExtra("p");
                iCity = getIntent().getStringExtra("c");
                iDistrict = getIntent().getStringExtra("d");

                key = iProvince;

                upData("1", "2");
                break;
            case 2:
                mTitleTv.setText("城市");
                iProvince = getIntent().getStringExtra("p");
                iCity = getIntent().getStringExtra("c");
                iDistrict = getIntent().getStringExtra("d");

                key = iCity;

                upData(String.valueOf(getIntent().getIntExtra("parent_id", 0)), "3");
                break;
            case 3:
                mTitleTv.setText("地区");
                iProvince = getIntent().getStringExtra("p");
                iCity = getIntent().getStringExtra("c");
                iDistrict = getIntent().getStringExtra("d");

                key = iDistrict;

                upData(String.valueOf(getIntent().getIntExtra("parent_id", 0)), "4");
                break;
        }

        mAdapter = new ChoiceAddressAdapter(mContext, key);
        mList.setAdapter(mAdapter);
    }

    @Override
    protected void initListener() {
        setOnClickListener(R.id.back_btn);

        mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mAdapter.setIndex(i);

                if (mType == 3) {
                    modifyInfo(mAdapter.getItem(i).getRegion_name());
                } else {
                    Intent intent = new Intent(mContext, ChoiceAddressActivity.class);
                    if (mType == 1) {
                        intent.putExtra("type", 2);
                        intent.putExtra("province", mAdapter.getItem(i).getRegion_name());

                        intent.putExtra("p", iProvince);
                        intent.putExtra("c", iCity);
                        intent.putExtra("d", iDistrict);

                    } else if (mType == 2) {
                        intent.putExtra("type", 3);
                        intent.putExtra("province", getIntent().getStringExtra("province"));
                        intent.putExtra("city", mAdapter.getItem(i).getRegion_name());

                        intent.putExtra("p", iProvince);
                        intent.putExtra("c", iCity);
                        intent.putExtra("d", iDistrict);
                    }

                    intent.putExtra("parent_id", mAdapter.getItem(i).getRegion_id());
                    startActivityForResult(intent, CHOICE_ADDRESS);
                }
            }
        });
    }

    @Override
    public void treatClickEvent(int id) {
        switch (id) {
            case R.id.back_btn:
                appFinish();
                break;
        }
    }

    private void modifyInfo(String area) {
        loadingDialog = new DialogUtil().showGifdialog(mContext);
        loadingDialog.show();

        initParameter();
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("province", getIntent().getStringExtra("province"));
        mParams.put("city", getIntent().getStringExtra("city"));
        mParams.put("district", area);

        district = area;

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.MODIFY_USER_INFO),
                AsRes.MODIFY_USER_INFO, mParams, BaseEntity.class);
    }

    private void upData(String id, String type) {
        initParameter();
        mParams.put("userid", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("parent_id", id);
        mParams.put("region_type", type);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_REGION),
                AsRes.GET_REGION, mParams, ChoiceAddressEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        if (client.getUrlIdentifier() == AsRes.GET_REGION) {
            ChoiceAddressEntity entity = (ChoiceAddressEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                if (mType == 1) {
                    key = iProvince;
                }

                if (mType == 2) {
                    key = iCity;
                }

                if (mType == 3) {
                    key = iDistrict;
                }

                int index = processIndex(entity.getData(), key);
                mAdapter.setIndex(index);
                mAdapter.setData(entity.getData());
            } else {
                showToast(entity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.MODIFY_USER_INFO) {
            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }

            BaseEntity entity = (BaseEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                showToast("所在地修改成功");
                setResult(CHOICE_ADDRESS);
                appFinish();


                UserInfoEntity.DataBean dataBean = OAuthUtils.getInstance().getUserInfo();
                dataBean.setProvince(getIntent().getStringExtra("province"));
                dataBean.setCity(getIntent().getStringExtra("city"));
                dataBean.setDistrict(district);

                OAuthUtils.getInstance().setUserInfo(dataBean);
            } else if (entity.getStatus() == 10005) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, "");
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, "");
                OAuthUtils.getInstance().cleanUserInfo();

                showToast("登录信息已过期，请重新登录");
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);

                setResult(50);
                appFinish();
            } else {
                showToast(entity.getMsg());
            }
        }
    }

    private int processIndex(List<ChoiceAddressEntity.DataBean> data, String key) {
        int index = 0;

        if (key != null) {
            for (int i = 0; i < data.size(); i++) {
                if (key.equalsIgnoreCase(data.get(i).getRegion_name())) {
                    return i;
                }
            }
        }

        return index;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CHOICE_ADDRESS && resultCode == CHOICE_ADDRESS) {
            setResult(CHOICE_ADDRESS);
            appFinish();
        } else if (requestCode == CHOICE_ADDRESS && resultCode == 50) {
            setResult(50);
            appFinish();
        }
    }
}